<template>
    <div>
        <van-search
            v-model="q"
            shape="round"
            background="#4fc08d"
            placeholder="请输入搜索关键词"
        />
        <van-pull-refresh v-model="refresh" @refresh="onRefresh">
            <van-list
                :loading="loading"
                :finished="finished"
                finished-text="没有更多了"
                @load="_page++"
                >
                <ul>
                    <li v-for="item in list" :key="item.id">
                        <img :src="item.img" alt="">
                        <span>{{ item.title }}</span>
                        <span>{{ item.price }}</span>
                    </li>
                </ul>
            </van-list>
        </van-pull-refresh>
    </div>
</template>

<script setup>
import axios from 'axios';
import { onMounted, ref, watch } from 'vue';

// 当前页码
const _page = ref(1)
const q = ref('')
const list = ref([])
const loading = ref(true);
const finished = ref(false);
const refresh = ref(false)

const onRefresh = () =>{
    _page.value = 1;
    refresh.value = false;
}

// 请求数据
const getData = () =>{
    loading.value =true
    axios.get('/api/cartList', { params: { _page: _page.value, q: q.value } }).then(res =>{
        if(res.status === 200){
            // 如果是在第一页，请求到的数据就直接存进数组，如果不是第一页，就把之前的数据和新请求到的数据进行拼接
            if(_page.value === 1){
                list.value = res.data
            } else {
                list.value = list.value.concat(res.data)
            }
            loading.value = false
            if(res.data.length === 0){
                finished.value = true
            } else {
                finished.value = false
            }
        }
    })
}

onMounted(()=>{
    getData()
})

// 监听输入框的值
watch(q, ()=>{
    _page.value = 1
    finished.value = false
    getData()
})

// 监听页码
watch(_page, ()=>{
    getData()
})
</script>

<style scoped>
.van-search{
    position: fixed;
    left: 0;
    top: 0;
    width: 100vw;
    z-index: 99;
}
.van-list{
    margin-bottom: 60px;
}
ul{
    margin-top: 60px;
}
</style>